/**
 * Zhznet.com Inc.
 * Copyright (c) 2004-2011 All Rights Reserved.
 */
package com.zhz.project.main.socolar.wenzhang.util;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.util.getWebContent;

/**
 * 提交参数演示
 * 该程序连接到一个用于查询手机号码所属地的页面
 * 以便查询号码段1330227所在的省份以及城市
 *
 * @author Liwei
 * @version $Id: SimpleHttpClient.java, v 0.1 2011-1-22 上午10:06:29 Liwei Exp $
 */
public class PostTxtCodeToServerClient {

    private static Log logger = LogFactory.getLog(PostTxtCodeToServerClient.class);

    public static boolean check(String url, String code, String cookie, String Referer)
                                                                                       throws IOException {
        HttpClient client = new HttpClient();
        client.getHostConfiguration().setProxy(getWebContent.proxy, getWebContent.port);

        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

        // 使用 POST 方式提交数据   
        HttpMethod method = new PostMethod(url);

        NameValuePair __VIEWSTATE = new NameValuePair(
                "__VIEWSTATE",
                "/wEPDwULLTEzMzE5MDUyNjEPZBYCAgEPZBYCAgEPD2QWAh4JT25LZXlEb3duBRNqYXZhc2NyaXB0OnNibWl0KCk7ZGToSnaRAC++VyPhLHRjKav92IaIZg==");
        NameValuePair __EVENTVALIDATION = new NameValuePair(
                "__EVENTVALIDATION",
                "/wEWAwLch/H2DwLChPzDDQKxoLakDtRQnvYQSgTUkM6AlTorf+j01sc5");
        NameValuePair txtCode = new NameValuePair("txtCode", code);
        NameValuePair btnConf = new NameValuePair("btnConf", "%E7%A1%AE%E8%AE%A4");

        ((PostMethod) method).setRequestBody(new NameValuePair[] { __VIEWSTATE, __EVENTVALIDATION,txtCode, btnConf });
        //        ((PostMethod) method).setRequestBody(new NameValuePair[] { txtCode, btnConf });
        List<Header> headers = new ArrayList<Header>();

        headers.add(new Header("Cookie", "ASP.NET_SessionId=" + cookie));
        headers.add(new Header("Referer", URLEncoder.encode(Referer)));
        headers
            .add(new Header("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"));

        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);

        client.executeMethod(method);
        String response = method.getResponseBodyAsString();
        method.releaseConnection();

        // 检查是否重定向
        int statuscode = method.getStatusCode();

        if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
            || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER)
            || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            // 读取新的 URL 地址   
            Header header = method.getResponseHeader("location");
            if (header != null) {
                String newuri = header.getValue();

                //返回的location有问题，并不是全部的链接
                if (StringUtil.contains(newuri, "pid")) {
                    newuri = StringUtil.substring(url, StringUtil.indexOf(url, "?") + 3);
                }
                GetMethod redirect = new GetMethod(newuri);
                client.executeMethod(redirect);
                response = redirect.getResponseBodyAsString();

                redirect.releaseConnection();
                if (StringUtil.isNotBlank(response)) {
                    response = new String(response.getBytes("UTF-8"));
                } else {
                    return false;
                }
                //打印返回的信息
                //                System.out.println(response);

                //                logger.info("--ok--newuri=" + newuri);
                //                logger.info("--ok--content=\r\n" + response);

                return true;
            }
            return true;
        }
        method.releaseConnection();
        return false;
    }
}
